package com.woniuxy.weixindemo.task;

import com.woniuxy.weixindemo.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 执行定时任务
 * <P> Date: 2022/5/31:19:59
 * <P> Description:
 */
@Component
// 开启定时任务 可以放在启动类上 这里只有一个任务 就放在这里
@EnableScheduling
@Slf4j
public class MyTask {

    @Resource
    private AsyncService asyncService;

    @Resource
    private ThreadPoolTaskExecutor asyncServiceExecutor;

    /**
     * 秒 分 时 日 月 周
     * 以秒为例
     * *：每秒都执行
     * 1-3：从第1秒开始执行，到第3秒结束执行
     * 0/3：从第0秒开始，每隔3秒执行1次
     * 1,2,3：在指定的第1、2、3秒执行
     * ?：不指定
     * 日和周不能同时制定，指定其中之一，则另一个设置为?
     */
    private final CountDownLatch countDownLatch = new CountDownLatch(2);
    private final CyclicBarrier cyclicBarrier = new CyclicBarrier(2);

    //    @Scheduled(cron = "0/5 * * * * ?")
    public void test() {
        log.info("执行线程定时任务");
        asyncService.executeAsync(cyclicBarrier);
        log.info("执行线程定时任务完毕 等待线程任务执行");
    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void t1() {
        Future<?> submit =
                asyncServiceExecutor.submit((Callable<Object>) () -> {
            log.warn("123");
            return "ok";
        }

        );
        try {
            System.out.println(submit.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

    }


    private static final ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();

    static {
        threadPoolTaskExecutor.initialize();
    }
    public static void submit(Callable<String> callable) throws ExecutionException, InterruptedException {
        Future<String> future = threadPoolTaskExecutor.submit(callable);

        // 阻塞 等待结果
        log.debug(future.get());
    }

    public static Callable<String> main1() {
        return () -> {
            log.info("dsadasdas");
            return "okk";
        };
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        submit(main1());
    }
}
